from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request

from info import constants, db
from info.modules.news import news_blue
from info.utils.common import user_login_data
from info.models import News, Comment, CommentLike
from info.utils.response_code import RET


@news_blue.route('/comment_like', methods=["POST"])
@user_login_data
def set_comment_like():
    """评论点赞"""

    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 获取参数
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")


    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("add", "remove"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询评论数据
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论数据不存在")

    if action == "add":
        comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id, CommentLike.comment_id == comment_id).first()

        if not comment_like:
            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = g.user.id
        try:
            db.session.add(comment_like)
            comment.like_count += 1
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)

    else:
        comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id, CommentLike.comment_id == comment_id).first()
        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1
            db.session.commit()

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blue.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    user = g.user

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    news_id = request.json.get('news_id')
    comment_str = request.json.get("comment")
    parent_id = request.json.get("parent_id")

    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    # 初始化模型，保存数据
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_str
    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存评论数据失败")

        # 返回响应
    return jsonify(errno=RET.OK, errmsg="评论成功", data=comment.to_dict())


@news_blue.route("/news_collect", methods=['POST'])
@user_login_data
def news_collect():
    user = g.user
    json_data = request.json
    news_id = json_data.get("news_id")
    action = json_data.get("action")

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("collect", "cancel_collect"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻数据不存在")

    if action == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blue.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):

    user = g.user
    news = []
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)
    if not news:
        # 返回数据未找到的页面
        abort(404)

    new_list = None
    try:
        # 取出排名前liu的新闻对象
        new_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 点击排行的新闻列表
    click_new_list = []
    for new in new_list:
        click_new_list.append(new)

    comments = []
    # 评论对象查询
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    comment_like_ids = []
    if user:
        comment_ids = [comment.id for comment in comments]

        comment_likes = CommentLike.query.filter(CommentLike.comment_id .in_(comment_ids), CommentLike.user_id == user.id).all()

        comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]

    comment_list = []


    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False
        if comment.id in comment_like_ids:

            comment_dict['is_like'] = True
        comment_list.append(comment_dict)

    news.clicks += 1
    # 判断是否收藏该新闻，默认值为 false
    is_collected = False
    # 判断用户是否收藏过该新闻
    if user:
        if news in user.collection_news:
            is_collected = True

    data = {
        "user_info": user.to_dict() if user else None,
        "news": news.to_dict(),
        "click_news_list": click_new_list,
        "is_collected": is_collected,
        "comments": comment_list

    }
    return render_template('news/detail.html', data=data)
